package com.heba.greenmulu.diary;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.Icon;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.FetchPlaceRequest;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.heba.Debug;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.diary.ItemAddressObject;
import com.heba.bean.diary.ItemTagInfoObject;
import com.heba.bean.diary.ItemUploadPhotoObject;
import com.heba.bean.diary.ItemUserInfoObject;
import com.heba.bean.product.ItemProductInfoObject;
import com.heba.bean.product.ItemProductSimilarObject;
import com.heba.bean.search.AccountSearchObject;
import com.heba.bean.search.HashTagSearchObject;
import com.heba.config.CommonConfig;
import com.heba.decoration.GridVerticalSpaceItemDecoration;
import com.heba.dialog.CustomDialogView;
import com.heba.event.MessageEvent;
import com.heba.fragment.diary.DiarySearchFragment;
import com.heba.fragment.search.SearchAccountFragment;
import com.heba.fragment.search.SearchHashTagFragment;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.MemberShipHelper;
import com.heba.helper.UploadPhotoHelper;
import com.heba.helper.callback.PhotoCompressListener;
import com.heba.helper.callback.VideoUploadListener;
import com.heba.loader.MyGlideEngine;
import com.heba.permission.PermissionHelper;
import com.heba.popupwindow.DiaryAddPhotoPopupWindow;
import com.heba.popupwindow.callback.DiaryAddPhotoCilckListener;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.utils.ImageTools;
import com.heba.utils.ToastShow;
import com.heba.view.FlowLayout;
import com.heba.view.MyRatingBarView;
import com.heba.view.RoundImageView;
import com.heba.view.ViewSpan;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.w3c.dom.Text;

import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import easypermission.EasyPermission;
import easypermission.GrantResult;
import easypermission.NextAction;
import easypermission.Permission;
import easypermission.PermissionRequestListener;
import easypermission.RequestPermissionRationalListener;

/**
 * 新增日记
 * Created by jason on 2020/1/21.
 */
public class ItemDiaryAddActivity extends BaseActivity {

    public static final String AUTHORITY = "com.heba.provider";

    public static final int REQUEST_CODE_CHOOSE = 23;

    public static final int REQUEST_CODE_VIDEO = 22;

    public static final int REQUEST_CODE_TAKE_PICTURE = 21;

    private PlacesClient placesClient;
    /**
     * 图片可选择的最大数量
     */
    public static final int MAX_SELECT = 9;

    private View view_background;
    private ScrollView scrollView;
    private EditText et_content;
    private RecyclerView recyclerView;
    private View view_label_friend;
    private View view_tag;
    private FlowLayout fl_tag_view;
    private View view_product;
    private View view_product1;

    /**
     * 添加地址title,右边title,箭头Image
     * 地点名称，地址详情
     */
    private TextView addTitle;
    private TextView rightTitle;
    private ImageView rightIcon;
    private TextView addressnameTV;
    private TextView addressDetailTV;
    private ItemAddressObject itemAddressObject;
    private AutocompletePrediction autocompletePrediction;
    private Place detailplace;

    private QuickAdapter recycleAdapter;

    /**
     * 搜尋 賬戶 標籤
     */
    private DiarySearchFragment searchFragment;
    private boolean starSearch = false;
    private ConstraintLayout constraintLayout;
    private StringBuffer alertUserString;
    /**
     * 照片彈出框
     */
    private DiaryAddPhotoPopupWindow addPhotoPopupWindow;

    private File tempFile;     //拍照图片路径

    private File videoFile;    //视频文件路径

    /**
     * 图片选择集合 list
     */
    private UploadPhotoHelper photoHelper;
    private List<ItemUploadPhotoObject> uploadPhotoObjects;
    private ItemUploadPhotoObject uploadIconObject;  //顯示上傳圖片的object

    /**
     * 话题标签集合 list
     */
    private List<HashTagSearchObject> tagInfoObjectList;
    /**
     * 賬戶集合 list
     */
    public List<AccountSearchObject> usetInfoObjectList;

    /**
     * 相關產品object
     */
    private ItemProductSimilarObject productSimilarObject;
    private boolean hasProduct = false;

    /**
     * 接收的数据
     */
    private int type = 1;   // 0表示新增产品评价  1表示新增日记 (默认新增日记)
    private ItemProductInfoObject productInfoObject;   //新增产品评价时接收的产品信息

    /**
     * 上传日记的参数
     */
    private String productID = "";
    private int star = 5;
    /**
     * 搜索賬戶和標籤的列表
     */

    public void setSearchStateAndData(boolean b,Object obj){
        starSearch = b;

        if (type==1){
            String[] stringArray = et_content.getText().toString().split("@");
            StringBuffer sb = new StringBuffer();
            sb.append(et_content.getText());
            AccountSearchObject accountObj = (AccountSearchObject) obj;
            usetInfoObjectList.add(accountObj);
            int index = et_content.getSelectionStart();
            sb.delete(index-alertUserString.length(),index);
            sb.insert(index-alertUserString.length(),"@"+accountObj.getAccount()+" ");
            et_content.setText(sb.toString());
            et_content.setSelection(index-alertUserString.length()+accountObj.getAccount().length()+2);
            alertUserString.delete(0,alertUserString.length());

        }else{
            String[] stringArray = et_content.getText().toString().split("#");
            StringBuffer sb = new StringBuffer();
            sb.append(et_content.getText());
            HashTagSearchObject hashTagObj =  (HashTagSearchObject) obj;
            tagInfoObjectList.add(hashTagObj);
            int index = et_content.getSelectionStart();
            sb.delete(index-alertUserString.length(),index);
            sb.insert(index-alertUserString.length(),hashTagObj.getContent()+" ");
            et_content.setText(sb.toString());
            et_content.setSelection(index-alertUserString.length()+hashTagObj.getContent().length()+1);
            alertUserString.delete(0,alertUserString.length());

        }
        starSearch = false;
        constraintLayout.setVisibility(View.GONE);

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_add);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initTopbar();
        findViewById();
        initView();
        initPopupWindow();
    }

    @Override
    protected void findViewById() {
        view_background = findViewById(R.id.view_background);
        scrollView = findViewById(R.id.scrollView);
        et_content = findViewById(R.id.et_content);
        recyclerView = findViewById(R.id.recyclerView);
        view_label_friend = findViewById(R.id.view_label_friend);
        view_tag = findViewById(R.id.view_tag);
        fl_tag_view = view_tag.findViewById(R.id.fl_tag_view);
        view_product = findViewById(R.id.view_product);
        view_product1 = findViewById(R.id.view_product1);
        addTitle = view_tag.findViewById(R.id.address_title);
        rightTitle = view_tag.findViewById(R.id.tv_text3);
        rightIcon = view_tag.findViewById(R.id.right_image);
        addressnameTV = view_tag.findViewById(R.id.address_text1);
        addressDetailTV = view_tag.findViewById(R.id.address_text2);




    }
    public static final String GOOGLE_PLACE_API_KEY = "AIzaSyC0DjOsaJCzZaVM-ze19pMfFT48sc3jCno";
    @Override
    protected void initView() {
        tagInfoObjectList = new ArrayList<>();
        usetInfoObjectList = new ArrayList<>();
        productSimilarObject = new ItemProductSimilarObject();
        alertUserString = new StringBuffer();
        photoHelper = new UploadPhotoHelper(this);
        TextView textView = findViewById(R.id.et_content);
        Places.initialize(this,GOOGLE_PLACE_API_KEY , Locale.TRADITIONAL_CHINESE);
        placesClient = Places.createClient(this);
        textView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString();
                if (start >=str.length()){
                    System.out.print("++=+++++++"+start+"--------"+str.charAt(start-1));
                    if ('@'== (str.charAt(start-1))||'#'== (str.charAt(start-1))){
                        starSearch = false;
                        constraintLayout.setVisibility(View.GONE);
                    }
                }else{
                    if ('@'== (str.charAt(start))){
                        type = 1;
                        searchFragment.setType(1);
                        starSearch = true;
                        constraintLayout.setVisibility(View.VISIBLE);

                    }
                    if ('#' == str.charAt(start)){
                        type = 2;
                        searchFragment.setType(2);
                        starSearch = true;
                        constraintLayout.setVisibility(View.VISIBLE);
                    }
                    if (starSearch){
                        StringBuffer sb = new StringBuffer();
                        sb.append(str);

                        alertUserString.append(sb.substring(start,start +count));
                        String tempStr = alertUserString.toString().replace("@","");
                        searchFragment.refreshData(tempStr);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        initSearchView();
        /**
         * 接收数据参数
         */
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            type = bundle.getInt(CommonConfig.TYPE, 1);
            productInfoObject = (ItemProductInfoObject) bundle.getSerializable(CommonConfig.PRODUCT_OBJECT);
        }

        txt_right.setText(getResources().getString(R.string.diary_send));
        ((TextView) view_label_friend.findViewById(R.id.tv_text1)).setText(R.string.diary_label_friend);
        ((TextView) view_label_friend.findViewById(R.id.tv_text2)).setText("");
        ((TextView) view_tag.findViewById(R.id.address_title)).setText(R.string.diary_location);
        ((TextView) view_tag.findViewById(R.id.tv_text3)).setText(R.string.add_diary_location);
        ((TextView) view_product.findViewById(R.id.tv_text1)).setText(R.string.diary_product);
        ((TextView) view_product.findViewById(R.id.tv_text2)).setText(R.string.diary_product_text);

        /**
         * 判断是新增产品评价还是新增日记
         * 从而显示不同界面
         */
        if (type == 0) {
            //新增評價
            txt_title.setText(getResources().getString(R.string.diary_review_add));
            view_product.setVisibility(View.INVISIBLE);
            view_product1.setVisibility(View.VISIBLE);
            ToastShow.displayToast(this, this.getResources().getString(R.string.diary_photo_tips));
        } else {
            //新增日記
            txt_title.setText(getResources().getString(R.string.diary_add));
            view_product.setVisibility(View.VISIBLE);
            view_product1.setVisibility(View.INVISIBLE);
        }

        uploadPhotoObjects = new ArrayList<>();
        //默認添加顯示上傳按鈕
        uploadIconObject = new ItemUploadPhotoObject();
        uploadIconObject.setImageType(ItemUploadPhotoObject.SHOW_IMAGE_ICON);
        uploadPhotoObjects.add(uploadIconObject);

        //设置显示图片宽高
        final int imageWidth = (DensityUtils.getWidth(this) - DensityUtils.dip2px(this, 40)) / 4;

        recycleAdapter = new QuickAdapter<ItemUploadPhotoObject>(uploadPhotoObjects) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_upload_video_round_image;
            }

            @Override
            public void convert(VH holder, ItemUploadPhotoObject data, int position) {
                RoundImageView imageView = holder.getView(R.id.roundImage);
                ImageView iv_delete = holder.getView(R.id.iv_delete);
                ImageView iv_play = holder.getView(R.id.iv_play);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(imageWidth, imageWidth);
                holder.getView(R.id.constrainLayout).setLayoutParams(params);

                iv_play.setVisibility(View.GONE);
                if (data.getType().equals(ItemUploadPhotoObject.TYPE_PICTURE)) {
                    //上传图片的处理
                    if (data.getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_ICON) {
                        //显示上传按钮
                        holder.itemView.setTag(1);
                        iv_delete.setVisibility(View.GONE);
                        Glide.with(ItemDiaryAddActivity.this).load(R.drawable.icon_scan_add_pic).into(imageView);
                    } else if (data.getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_PATH) {
                        //加载图片地址
                        holder.itemView.setTag(2);
                        iv_delete.setVisibility(View.VISIBLE);
                        if (!data.getPhotoPath().isEmpty()) {
                            Glide.with(ItemDiaryAddActivity.this).load(new File(data.getPhotoPath())).into(imageView);
                        }
                    }
                } else {
                    //上传视频的处理
                    holder.itemView.setTag(3);
                    iv_delete.setVisibility(View.VISIBLE);
                    iv_play.setVisibility(View.VISIBLE);
                    if (!data.getPhotoPath().isEmpty()) {
                        Glide.with(ItemDiaryAddActivity.this).load(new File(data.getPhotoPath())).into(imageView);
                    }
                }

                /**
                 * 删除图片或视频
                 */
                iv_delete.setTag(position);
                iv_delete.setOnClickListener(v -> {
                    int deletPos = (int) v.getTag();
                    uploadPhotoObjects.remove(deletPos);
                    refreshPhotoGridView();
                });

                /**
                 * 圖片點擊處理
                 */
                holder.itemView.setOnClickListener(v -> {
                    int tag = (int) v.getTag();
                    Bundle bundle1 = new Bundle();
                    switch (tag) {
                        case 1:
                            //显示popup弹出框
                            getCameraPermission();
                            break;
                        case 2:
                            //进入图片编辑页面
                            if (!uploadPhotoObjects.isEmpty()) {
                                List<String> paths = new ArrayList<>();
                                for (ItemUploadPhotoObject object : uploadPhotoObjects) {
                                    if (object.getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_PATH) {
                                        paths.add(object.getPhotoPath());
                                    }
                                }
                                bundle1.putInt(CommonConfig.TYPE, CommonConfig.TYPE_EDIT);
                                bundle1.putSerializable(CommonConfig.DIARY_PATH_LIST, (Serializable) paths);
                                bundle1.putSerializable(CommonConfig.DIARY_IMAGE_LIST, (Serializable) uploadPhotoObjects);
                                openActivity(ItemDiaryPhotoEditActivity.class, bundle1);
                            }

                            break;
                        case 3:
                            //进入预览视频页面
                            bundle1.putString(CommonConfig.DIARY_VIDEO, data.getVideoPath());
                            openActivity(ItemDiaryVideoPreviewActivity.class, bundle1);
                            break;
                        default:
                            break;
                    }
                });
            }


            @Override
            public int getItemCount() {
                return uploadPhotoObjects.size();
            }
        };

        /**
         * 设置layoutManager布局
         */
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        /**
         * 设置item间隔
         */
        recyclerView.addItemDecoration(new GridVerticalSpaceItemDecoration(DensityUtils.dip2px(this, 5), 4));
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        /**
         * 监听滚动事件 回收键盘
         */
        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                DensityUtils.hideSoftWindow(ItemDiaryAddActivity.this, et_content);
            }
        });

        /**
         * 返回提示框
         */
        img_back.setOnClickListener(v -> {
            new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                @Override
                public void onYesClick() {
                    finishActivity();
                }

                @Override
                public void onNoClick() {

                }
            }).showDialogWithButton(this, getResources().getString(R.string.diary_dialog_review_title), getResources().getString(R.string.diary_dialog_review_content),
                    getResources().getString(R.string.diary_dialog_review_discard), getResources().getString(R.string.diary_dialog_review_keep));
        });

        /**
         * 标贴朋友
         */
        view_label_friend.setOnClickListener(v -> {
            if (!uploadPhotoObjects.isEmpty() && uploadPhotoObjects.get(0).getImageType() != ItemUploadPhotoObject.SHOW_IMAGE_ICON) {
                Bundle bundle1 = new Bundle();
                bundle1.putSerializable(CommonConfig.DIARY_IMAGE_LIST, (Serializable) uploadPhotoObjects);
                bundle1.putInt(CommonConfig.POSITION, 0);
                openActivity(ItemDiaryFriendTagPhotoActivity.class, bundle1);
            }
        });

        /**
         * 添加话题
         */
        view_tag.setOnClickListener(v -> {
//            Bundle bundle1 = new Bundle();
//            bundle1.putSerializable(CommonConfig.TAG_LIST, (Serializable) tagInfoObjectList);
            openActivity(DiarySearchAddressActivity.class);
        });

        /**
         * 添加产品
         */
        view_product.setOnClickListener(v -> {
            openActivity(ItemDiaryProductAddActivity.class);
        });

        /**
         * 發佈日記
         */
        txt_right.setOnClickListener(v -> {
            if (et_content.getText().toString().trim().isEmpty()) {
                ToastShow.displayToast(this, getResources().getString(R.string.diary_content_tips));
                return;
            }

            if (type == 1) {
                //新增日记 必须上传图片
                if (uploadPhotoObjects.size() == 1 && uploadPhotoObjects.get(0).getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_ICON) {
                    ToastShow.displayToast(this, getResources().getString(R.string.diary_upload_photo_tips));
                    return;
                }
            }

            /**
             * 新增产品评价 允许不上传图片
             */
            if (type == 0 && uploadPhotoObjects.size() == 1 && uploadPhotoObjects.get(0).getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_ICON) {
                uploadDiaryData(null);
                return;
            }

            /**
             * 执行上传视频操作
             */
            if (uploadPhotoObjects.size() == 1 && uploadPhotoObjects.get(0).getType().equals(ItemUploadPhotoObject.TYPE_VIDEO)) {
                loading.Start();
                photoHelper.uploadVideo(uploadPhotoObjects, new VideoUploadListener() {
                    @Override
                    public void onUploadSuccess(List<ItemUploadPhotoObject> list) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                loading.End();
                                /**
                                 * 视频上传成功 执行日记上传API
                                 */
                                uploadDiaryData(list);
                            }
                        });
                    }

                    @Override
                    public void onUploadFailure() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                loading.End();
                            }
                        });
                    }
                });
                return;
            }

            /**
             * 执行上传图片操作
             * 壓縮和上傳圖片
             */
            loading.Start();
            photoHelper.compressPhoto(uploadPhotoObjects, new PhotoCompressListener() {
                @Override
                public void onCompressStart() {
                }

                @Override
                public void onCompressSuccess() {
                    loading.End();
                }

                @Override
                public void onCompressError() {
                    loading.End();
                    ToastShow.displayToast(ItemDiaryAddActivity.this, getResources().getString(R.string.diary_compress_error));
                }

                @Override
                public void onUploadSuccess(List<ItemUploadPhotoObject> list) {
                    Debug.Log("onUploadSuccess", "圖片全部上傳成功!");
                    runOnUiThread(() -> {
                        loading.End();

                        /**
                         * 執行日記上傳api 上傳日記內容、圖片和話題標籤等等
                         */
                        uploadDiaryData(list);
                    });

                }

                @Override
                public void onUploadFailure() {
                    Debug.Log("onUploadFailure", "圖片上傳失敗!");
                    runOnUiThread(() -> {
                        loading.End();
                        ToastShow.displayToast(ItemDiaryAddActivity.this, getResources().getString(R.string.diary_upload_failure));
                    });
                }
            });
        });

    }
    private void initSearchView(){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        searchFragment = DiarySearchFragment.newInstance("");
        transaction.add(R.id.fragment_layout, searchFragment);
        constraintLayout = findViewById(R.id.fragment_layout);
        constraintLayout.setVisibility(View.GONE);
        searchFragment.itemDiaryAddActivity = this;

        transaction.show(searchFragment);
        transaction.commit();
    }
    /**
     * 照片彈出框
     */
    private void initPopupWindow() {
        addPhotoPopupWindow = new DiaryAddPhotoPopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dip2px(this, 226));

        addPhotoPopupWindow.setOnDiaryAddPhotoClickListener(new DiaryAddPhotoCilckListener() {
            @Override
            public void onAlbumClick() {
                /**
                 * 相册
                 */
                int count;
                if (uploadPhotoObjects.contains(uploadIconObject)) {
                    count = uploadPhotoObjects.size() - 1;
                } else {
                    count = uploadPhotoObjects.size();
                }

                Matisse.from(ItemDiaryAddActivity.this)
                        .choose(MimeType.ofImage(), false)
                        .countable(true)
//                        .capture(true)
//                        .captureStrategy(
//                                new CaptureStrategy(true, "com.zhihu.matisse.sample.fileprovider"))
                        .maxSelectable(MAX_SELECT - count)
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.7f)
                        .imageEngine(new MyGlideEngine())
                        .setOnSelectedListener((uriList, pathList) -> {
                            Log.e("onSelected", "onSelected: pathList=" + pathList);
                        })
                        .showSingleMediaType(true)
                        .originalEnable(false)
                        .maxOriginalSize(10)
//                        .autoHideToolbarOnSingleTap(true)
                        .setOnCheckedListener(isChecked -> {
                            Log.e("isChecked", "onCheck: isChecked=" + isChecked);
                        })
                        .theme(R.style.Matisse_GreenMulu)
                        .forResult(REQUEST_CODE_CHOOSE);
            }

            @Override
            public void onTakePhotoClick() {
                /**
                 * 拍照
                 */
                takePhoto();
            }

            @Override
            public void onTakeVideoClick() {
                /**
                 * 拍摄视频
                 */
                takeVideo();
            }

            @Override
            public void onCancelClick() {

            }
        });

        addPhotoPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 获取摄像头,读取文件权限
     */
    private void getCameraPermission() {




        EasyPermission.with(this)
                .addPermissions(easypermission.Permission.WRITE_EXTERNAL_STORAGE)      //申请定位权限组
                .addPermissions(easypermission.Permission.Group.CAMERA)
                .addPermissions(easypermission.Permission.RECORD_AUDIO)


                .request(new PermissionRequestListener() {

                    @Override
                    public void onGrant(Map<String, GrantResult> result) {
                        view_background.setVisibility(View.VISIBLE);

                        /**
                         * 判断是否隐藏上传视频的按钮
                         */
                        if (!uploadPhotoObjects.isEmpty()) {
                            if (uploadPhotoObjects.size() > 1 && uploadPhotoObjects.get(0).getType().equals(ItemUploadPhotoObject.TYPE_PICTURE)) {
                                addPhotoPopupWindow.setVideoVisible(false);
                            } else {
                                addPhotoPopupWindow.setVideoVisible(true);
                            }
                        }
                        addPhotoPopupWindow.showAtLocation(recyclerView, Gravity.BOTTOM, 0, 0);
                    }

                    @Override
                    public void onCancel(String stopPermission) {
                        //在addRequestPermissionRationaleHandler的处理函数里面调用了NextAction.next(NextActionType.STOP,就会中断申请过程，直接回调到这里来
                    }
                });
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        //拍照图片文件路径
        tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());

        Uri imageUri = Uri.fromFile(tempFile);
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(
                MediaStore.EXTRA_OUTPUT,
                imageUri);
        startActivityForResult(cameraIntent, REQUEST_CODE_TAKE_PICTURE);
    }

    /**
     * 拍摄视频
     */
    private void takeVideo() {
        videoFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getVideoName());
//        Uri fileUri = Uri.fromFile(videoFile);
        Uri fileUri = FileProvider.getUriForFile(this, AUTHORITY, videoFile);
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);  //授予临时读取文件的权限
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 15);     //限制的录制时长 以秒为单位
//        intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 1024);        //限制视频文件大小 以字节为单位
//        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);      //设置拍摄的质量0~1
//        intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, false);        // 全屏设置
        Debug.Log(TAG, "VideoUri: " + fileUri.toString());
        startActivityForResult(intent, REQUEST_CODE_VIDEO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = new Bundle();
            switch (requestCode) {
                case REQUEST_CODE_CHOOSE:
                    /**
                     * 调用知乎图片库，添加选择的图片
                     */
                    if (data != null) {
                        List<String> paths = Matisse.obtainPathResult(data);
                        bundle.putInt(CommonConfig.TYPE, CommonConfig.TYPE_ALBUM);
                        bundle.putSerializable(CommonConfig.DIARY_PATH_LIST, (Serializable) paths);
                        bundle.putSerializable(CommonConfig.DIARY_IMAGE_LIST, (Serializable) uploadPhotoObjects);
                        openActivity(ItemDiaryPhotoEditActivity.class, bundle);
                    }

//                    if (data != null) {
//                        for (int i = 0; i < Matisse.obtainPathResult(data).size(); i++) {
//                            ItemUploadPhotoObject object = new ItemUploadPhotoObject();
//                            object.setImageType(ItemUploadPhotoObject.SHOW_IMAGE_PATH);
//                            object.setPhotoPath(Matisse.obtainPathResult(data).get(i));
//                            uploadPhotoObjects.add(uploadPhotoObjects.size() - 1, object);
//                        }
//
//                        Log.d("Matisse", "Uris: " + Matisse.obtainResult(data));
//                        Log.d("Matisse", "Paths: " + Matisse.obtainPathResult(data));
//                        Log.e("Matisse", "Use the selected photos with original: " + String.valueOf(Matisse.obtainOriginalState(data)));
//                    }
                    break;
                case REQUEST_CODE_TAKE_PICTURE:
                    /**
                     * 调用系统拍照
                     */
                    bundle.putInt(CommonConfig.TYPE, CommonConfig.TYPE_TAKE_PHOTO);
                    bundle.putString(CommonConfig.DIARY_PATH, tempFile.toString());
                    bundle.putSerializable(CommonConfig.DIARY_IMAGE_LIST, (Serializable) uploadPhotoObjects);
                    openActivity(ItemDiaryPhotoEditActivity.class, bundle);


//                    ItemUploadPhotoObject object = new ItemUploadPhotoObject();
//                    object.setImageType(ItemUploadPhotoObject.SHOW_IMAGE_PATH);
//                    object.setPhotoPath(tempFile.toString());
//                    uploadPhotoObjects.add(uploadPhotoObjects.size() - 1, object);
                    break;
                case REQUEST_CODE_VIDEO:
                    /**
                     * 调用系统录制视频
                     */
                    if (data != null && data.getData() != null) {
                        Uri uri = data.getData();
                        Debug.Log(TAG, "录制视频后保存的URI地址: " + uri);
                        Debug.Log(TAG, "录制视频后保存的本地地址: " + videoFile.getAbsolutePath());
                        //获取视频缩略图
                        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoFile.getAbsolutePath(), MediaStore.Images.Thumbnails.MINI_KIND);
                        if (null == bitmap) {
                            Debug.Log(TAG, "bitmap = null ");
                            return;
                        }
                        String thumbnailPath = ImageTools.savePhotoToSDCard(ItemDiaryAddActivity.this, bitmap, ImageTools.getUploadPathFolder(), ImageTools.getFileName(), false);
                        ItemUploadPhotoObject object1 = new ItemUploadPhotoObject();
                        object1.setType(ItemUploadPhotoObject.TYPE_VIDEO);
                        object1.setPhotoPath(thumbnailPath);
                        object1.setVideoPath(videoFile.getAbsolutePath());
                        uploadPhotoObjects.set(0, object1);
                        //回收bitmap
                        if (null != bitmap && !bitmap.isRecycled()) {
                            bitmap.recycle();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshUI();
    }

    /**
     * 刷新UI
     */
    private void refreshUI() {

        refreshPhotoGridView();

//        refreshTagView();

        refreshProductView();

    }

    /**
     * 刷新選擇的圖片UI
     */
    private void refreshPhotoGridView() {
        /**
         * 判断是否显示标贴朋友按钮
         */
        if (!uploadPhotoObjects.isEmpty()) {
            if (uploadPhotoObjects.get(0).getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_ICON ||
                    uploadPhotoObjects.get(0).getType().equals(ItemUploadPhotoObject.TYPE_VIDEO)) {
                view_label_friend.setVisibility(View.GONE);
            } else {
                view_label_friend.setVisibility(View.VISIBLE);
            }
        } else {
            view_label_friend.setVisibility(View.GONE);
        }

        /**
         * 图片grid显示
         */
        if (!uploadPhotoObjects.isEmpty()) {
            //判断是视频的情况,因为用户只能上传一条视频
            if (uploadPhotoObjects.get(0).getType().equals(ItemUploadPhotoObject.TYPE_VIDEO)) {
                if (uploadPhotoObjects.contains(uploadIconObject)) {
                    //移除上传图片或视频的按钮
                    uploadPhotoObjects.remove(uploadIconObject);
                }
            } else {
                //上传图片
                if (uploadPhotoObjects.size() > MAX_SELECT) {
                    if (uploadPhotoObjects.contains(uploadIconObject)) {
                        uploadPhotoObjects.remove(uploadIconObject);
                    }
                } else {
                    if (!uploadPhotoObjects.contains(uploadIconObject)
                            && uploadPhotoObjects.size() < MAX_SELECT) {
                        uploadPhotoObjects.add(uploadIconObject);
                    }
                }
            }
        } else {
            //添加默认上传按钮icon
            if (!uploadPhotoObjects.contains(uploadIconObject)) {
                uploadPhotoObjects.add(uploadIconObject);
            }
        }

        /**
         * 刷新数据
         */
        if (uploadPhotoObjects != null) {
            recycleAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 刷新話題標籤UI
     */
    private void refreshTagView() {
        if (!tagInfoObjectList.isEmpty()) {
//            updateSelectTagFlowView(tagInfoObjectList);
        }
    }

    /**
     * 更新產品view
     */
    private void refreshProductView() {
        if (type == 1) {
            //日記頁面
            if (hasProduct) {
                productID = productSimilarObject.getProductID();
                showProductView(productSimilarObject, true);
            }
        } else if (type == 0) {
            //產品頁面
            if (productInfoObject != null) {
                ItemProductSimilarObject object = new ItemProductSimilarObject();
                object.setIcon(productInfoObject.getIcon());
                object.setBrandName(productInfoObject.getBrandName());
                object.setProductID(productInfoObject.getProductID());
                object.setPackageSize(productInfoObject.getPackageSize());
                object.setProductName(productInfoObject.getProductName());
                object.setPackageUnit(productInfoObject.getPackageUnit());
                object.setServingSize(productInfoObject.getServingSize());
                object.setServingSizeUnit(productInfoObject.getServingSizeUnit());
                object.setValuePerUnit(productInfoObject.getValuePerUnit());
                productID = object.getProductID();
                showProductView(object, false);
            }
        }
    }

    /**
     * 顯示產品UI
     *
     * @param object
     */
    private void showProductView(ItemProductSimilarObject object, boolean isDeleteShow) {
        star = 5;
        view_product.setVisibility(View.GONE);
        view_product1.setVisibility(View.VISIBLE);
        GlideUtil.loadImageWithDefaultPlaceHolder(this, object.getIcon(), view_product1.findViewById(R.id.iv_product));
        ((TextView) view_product1.findViewById(R.id.tv_product)).setText(object.getBrandName());
        ((TextView) view_product1.findViewById(R.id.tv_content)).setText(object.getProductName());
        ((TextView) view_product1.findViewById(R.id.tv_weight)).setText(String.format(getResources().getString(R.string.per_serving_size), object.
                getPackageSize(), object.getPackageUnit(), CommonUtils.subZeroAndDot(object.getServingSize()), object.getServingSizeUnit()));
        ImageView iv_delete = view_product1.findViewById(R.id.iv_delete);
        MyRatingBarView ratingBar = view_product1.findViewById(R.id.rb_rating);
        iv_delete.setVisibility(isDeleteShow ? View.VISIBLE : View.GONE);
        ratingBar.setStar(star);

        /**
         * 获取产品评分
         */
        ratingBar.setOnRatingChangeListener(ratingCount -> {
            star = (int) ratingCount;
        });

        /**
         * 删除产品
         */
        iv_delete.setOnClickListener(v -> {
            hasProduct = false;
            productID = "";
            view_product.setVisibility(View.VISIBLE);
            view_product1.setVisibility(View.GONE);
        });
    }

    /**
     * 更新选中的标签view
     *
     * @param list
     */
    private void updateSelectTagFlowView(List<ItemTagInfoObject> list) {
        fl_tag_view.removeAllViews();

        /**
         * 添加佈局參數
         */
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(this, 37));
        params.rightMargin = DensityUtils.dip2px(this, 5);
        params.bottomMargin = DensityUtils.dip2px(this, 5);
        for (int i = 0; i < list.size(); i++) {
            fl_tag_view.addView(updateSelectFlowRowView(list.get(i)), params);
        }
    }

    /**
     * @param object
     * @return
     */
    private View updateSelectFlowRowView(ItemTagInfoObject object) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_search_flow_with_delete_row1, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        ImageView iv_delete = view.findViewById(R.id.iv_delete);
        tv_text.setText(object.getHotTalk());
        iv_delete.setOnClickListener(v -> {
            tagInfoObjectList.remove(object);
//            updateSelectTagFlowView(tagInfoObjectList);
        });
        return view;
    }


    /**
     * 上传日记
     *
     * @param list
     */
    private static final String splitRegix = "@(.+)\\s";
    private static final String splitRegix2 = "#(.+)\\s";
    private void uploadDiaryData(List<ItemUploadPhotoObject> list) {
        /**
         * 篩選包含的用戶信息
         */
        String contentText = et_content.getText().toString();
        List<AccountSearchObject> tempUserList = new ArrayList<>();
        for (int i = 0; i < usetInfoObjectList.size();i++){
            AccountSearchObject obj = usetInfoObjectList.get(i);
            if (contentText.indexOf(obj.getAccount()) != -1){
                tempUserList.add(obj);
            }
        }
        usetInfoObjectList = tempUserList;
        /**
         * 篩選包含的話題信息
         */
        String[] hashTagList = contentText.split(splitRegix2);
        List<HashTagSearchObject> tempHashList = new ArrayList<>();
        for (int i = 0; i < tagInfoObjectList.size(); i ++){
            HashTagSearchObject obj = tagInfoObjectList.get(i);
            if (contentText.indexOf(obj.getContent()) != -1){
                tempHashList.add(obj);
            }
        }
        tagInfoObjectList = tempHashList;


        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {
                progressDialog.dismiss();
                //通知日記列表刷新數據
                EventBus.getDefault().post(new MessageEvent(CommonConfig.EVENT_REFRESH_DIARY_LIST));
                ToastShow.displayToast(ItemDiaryAddActivity.this, getResources().getString(R.string.diary_upload_success));
                finishActivity();
            }

            @Override
            public void Fail(String error) {
                progressDialog.dismiss();
                ToastShow.displayToast(ItemDiaryAddActivity.this, getResources().getString(R.string.diary_upload_failure));
            }
        }).uploadDiaryContent(ItemDiaryAddActivity.this, CommonUtils.getEncodeText(CommonUtils.removeBlankLine(et_content.getText().toString())), type, productID, star,
                photoHelper.generatePhotoPathJson(list), photoHelper.generateTagInfoJson(tagInfoObjectList),photoHelper.generateUserInfoJson(usetInfoObjectList),
                itemAddressObject==null?(autocompletePrediction==null?"":autocompletePrediction.getPrimaryText(null).toString()):itemAddressObject.getName(),
                itemAddressObject==null?(autocompletePrediction==null?"":autocompletePrediction.getSecondaryText(null).toString()):detailplace.getAddress(),
                detailplace==null?0:detailplace.getLatLng().latitude,detailplace==null?0:detailplace.getLatLng().longitude);
    }

    /**
     *接受到地址後更新界面
     */
    public void updateAddressView1(Object address){
        addTitle.setVisibility(View.INVISIBLE);
        rightTitle.setVisibility(View.INVISIBLE);
        addressnameTV.setVisibility(View.VISIBLE);
        addressDetailTV.setVisibility(View.VISIBLE);
        rightIcon.setImageResource(R.drawable.icon_diary_delete);
        if (address instanceof ItemAddressObject) {
            itemAddressObject = (ItemAddressObject) address;
            addressnameTV.setText(itemAddressObject.getName());
            addressDetailTV.setText(itemAddressObject.getVicinity());
            autocompletePrediction = null;
        }
        if(address instanceof AutocompletePrediction){
            autocompletePrediction = (AutocompletePrediction)address;
            addressnameTV.setText(autocompletePrediction.getPrimaryText(null));
            addressDetailTV.setText(autocompletePrediction.getSecondaryText(null));

            itemAddressObject = null;

        }
    }

    /**
     * 接收EventBus
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收话题标签数据
         */
        if (event.getEvent().equals(CommonConfig.TAG_LIST)) {
//            this.tagInfoObjectList = event.getTagInfoObjectList();
        }
        if (event.getEvent().equals(CommonConfig.DIARY_ADDRESS)){
            this.itemAddressObject = event.getAddressObject();
            final List<Place.Field> placeFields = Arrays.asList(Place.Field.ID,Place.Field.NAME,Place.Field.ADDRESS,Place.Field.LAT_LNG);
            final FetchPlaceRequest request = FetchPlaceRequest.newInstance(itemAddressObject.getPlace_id(), placeFields);

            progressDialog.show();
            placesClient.fetchPlace(request).addOnSuccessListener((response) -> {
                detailplace = response.getPlace();
                updateAddressView1(itemAddressObject);
                progressDialog.dismiss();
            }).addOnFailureListener((exception) -> {
                progressDialog.dismiss();
                if (exception instanceof ApiException) {
                    final ApiException apiException = (ApiException) exception;
                    Log.e(TAG, "Place not found: " + exception.getMessage());
                    final int statusCode = apiException.getStatusCode();
                    // TODO: Handle error with given status code.
                }
            });
        }
        if (event.getEvent().equals(CommonConfig.DIARY_ADDRESS_2)){
                this.autocompletePrediction = event.getPrediction();
            progressDialog.show();
            final List<Place.Field> placeFields = Arrays.asList(Place.Field.ID,Place.Field.NAME,Place.Field.ADDRESS,Place.Field.LAT_LNG);
            final FetchPlaceRequest request = FetchPlaceRequest.newInstance(autocompletePrediction.getPlaceId(), placeFields);
            placesClient.fetchPlace(request).addOnSuccessListener((response) -> {
                detailplace = response.getPlace();
                progressDialog.dismiss();
                updateAddressView1(autocompletePrediction);
            }).addOnFailureListener((exception) -> {
                progressDialog.dismiss();
                if (exception instanceof ApiException) {
                    final ApiException apiException = (ApiException) exception;
                    Log.e(TAG, "Place not found: " + exception.getMessage());
                    final int statusCode = apiException.getStatusCode();
                    // TODO: Handle error with given status code.
                }
            });
        }
        /**
         * 接收產品數據
         */
        if (event.getEvent().equals(CommonConfig.PRODUCT_OBJECT)) {
            hasProduct = true;
            productSimilarObject = event.getProductSimilarObject();
        }

        /**
         * 图片标记用户时,接收图片数据
         */
        if (event.getEvent().equals(CommonConfig.EVENT_UPLOAD_PHOTO_LIST)) {
            List<ItemUploadPhotoObject> list = event.getUploadPhotoObjectList();
            this.uploadPhotoObjects.clear();
            this.uploadPhotoObjects.addAll(0, list);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        placesClient = null;
        /**
         * 清理图片文件夹
         */
        ImageTools.deleteAllPhoto(ImageTools.getUploadPathFolder());
    }

}
